use crate::config::CONFIG;
use crate::feature::Base;
use crate::model::gaode_map::{Geo, Live, WeatherInfo};
use crate::model::WebSocketMessage;
use crate::util::request::get;
use serde::Deserialize;
use serde_json::json;
use crate::group::send_message_group;

#[derive(Deserialize, Debug)]
pub struct Weather {

}
impl Base for Weather {
    async fn send_message(content: Option<String>, web_socket_message: WebSocketMessage) {
        if let Some(content) = content {
            let address = content.replace("/当前天气 ", "");
            let live = match get_now_weather(address).await {
                Ok(live) => live,
                Err(err) => {
                    send_message_group(Some(err), web_socket_message).await;
                    return;
                }
            };
            let reply = format!(
                "\n地区：{}省\n当前气温为：{}℃\n当前天气为：{}\n空气湿度为：{}\n当前时间：{}",
                live.province.unwrap(),
                live.temperature.unwrap(), live.weather.unwrap(), live.humidity.unwrap(), live.reporttime.unwrap()
            );
            send_message_group(Some(reply), web_socket_message).await;
        }
    }
}

async fn get_now_weather(address: String) -> Result<Live, String> {
    let key = CONFIG.get_gaode_map().key;
    let city = match get_address_code(address).await {
        Ok(city) => city,
        Err(_) => {
            return Err(String::from("地区错误！"));
        }
    };
    let response = get("https://restapi.amap.com/v3/weather/weatherInfo", json!({
        "key": key,
        "city": city,
        "extensions": "base",
        "output": "JSON"
    })).await?;
    let weather_info = response.json::<WeatherInfo>().await.unwrap();
    match weather_info.lives {
        None => {
            Err(String::new())
        }
        Some(data) => {
            if data.len().eq(&0) {
                return Err(String::new());
            }
            let live = data.get(0).unwrap();
            Ok((*live).clone())
        }
    }
}

async fn get_address_code(address: String) -> Result<String, String> {
    let key = CONFIG.get_gaode_map().key;
    let response = get("https://restapi.amap.com/v3/geocode/geo", json!({
        "key": key,
        "address": address,
    })).await?;
    let geo = response.json::<Geo>().await.unwrap();
    match geo.geocodes {
        None => {
            Err(String::new())
        }
        Some(data) => {
            let geocode = data.get(0).unwrap();
            Ok(geocode.clone().adcode.unwrap_or_else(|| String::new()))
        }
    }
}

#[tokio::test]
async fn test_address() {
    let res = get_address_code("长沙市岳麓区".to_string()).await.unwrap();
    println!("res = {}", res);
}